package com.ffzl.cloud.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Base64;

import androidx.annotation.NonNull;

import com.ffzl.cloud.app.AppApplication;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

public class SPUtils {
     /* private SPUtils() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }*/

    private final SharedPreferences sp;

    private static class SPHolder{
        private static final SharedPreferences INSTANCE =
                AppApplication.getInstance().getSharedPreferences(getDefaultSharedPreferencesName(), Context.MODE_PRIVATE);
    }

    private SPUtils(@NonNull String name) {
        sp = getSharedPreferences(name);
    }

//    private SPUtils() {
//        sp = getDefaultSharedPreferences();
//    }

    public static SPUtils newInstance(String name) {
        return new SPUtils(name);
    }

    public static SPUtils getInstance() {
        return new SPUtils();
    }

    private static SharedPreferences getSharedPreferences(@NonNull String name) {
        return AppApplication.getInstance().getSharedPreferences(name, Context.MODE_PRIVATE);
    }

    private static String getDefaultSharedPreferencesName() {
        return AppApplication.getInstance().getPackageName() + "_preferences";
    }
    private static SharedPreferences getDefaultSharedPreferences() {
        return SPHolder.INSTANCE;
    }

    private SharedPreferences.Editor getEditor() {
        return sp.edit();
    }

    public SPUtils clear() {
        getEditor().clear().apply();
        return this;
    }

//    public SPUtils remove(String keyword){
//        getEditor().remove(keyword).apply();
//        return this;
//    }

    public <T> SPUtils save(String keyword, T value) {
        SharedPreferences.Editor editor = getEditor();
        if (value == null) {
            editor.remove(keyword).apply();
        } else if (value instanceof String) {
            editor.putString(keyword, (String) value).apply();
        } else if (value instanceof Integer) {
            editor.putInt(keyword, (Integer) value).apply();
        } else if (value instanceof Boolean) {
            editor.putBoolean(keyword, (Boolean) value).apply();
        } else if (value instanceof Long) {
            editor.putLong(keyword, (Long) value).apply();
        } else if (value instanceof Float) {
            editor.putFloat(keyword, (Float) value).apply();
        }
        return this;
    }

    public <T> T get(String keyword, T defValue) {
        T value;
        if (defValue instanceof String) {
            String s = sp.getString(keyword, (String) defValue);
            value = (T) s;
        } else if (defValue instanceof Integer) {
            Integer i = sp.getInt(keyword, (Integer) defValue);
            value = (T) i;
        } else if (defValue instanceof Long) {
            Long l = sp.getLong(keyword, (Long) defValue);
            value = (T) l;
        } else if (defValue instanceof Float) {
            Float f = sp.getFloat(keyword, (Float) defValue);
            value = (T) f;
        } else if (defValue instanceof Boolean) {
            Boolean b = sp.getBoolean(keyword, (Boolean) defValue);
            value = (T) b;
        } else {
            value = defValue;
        }
        return value;
    }




    private SPUtils() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }
    /**,退出登录不会清除全部clearAll*/
    private static final String CONFIG_COMMON = "com.fanwei.youguangtong.common";
    /**b通用的 ,保存退出清除的*/
    private static final String CONFIG_USER = "com.fanwei.youguangtong.appInfo";

    /**
     * 获取SharedPreferences实例对象
     * 通用的:一般不会清除信息
     */
    private static SharedPreferences getSharedPreference() {
        return AppApplication.getInstance().getSharedPreferences(CONFIG_COMMON, Context.MODE_PRIVATE);
    }

    /**
     * 获取SharedPreferences实例对象
     * 用户信息，退出账号清除信息
     */
    private static SharedPreferences getSharedPreferenceUser() {
        return AppApplication.getInstance().getSharedPreferences(CONFIG_USER, Context.MODE_PRIVATE);
    }
//**********************************************************************************************************************************************
    /**
     * 保存一个String类型的值！
     */
    public static void putStringUser(String key, String value) {
        SharedPreferences.Editor editor = getSharedPreferenceUser().edit();
        editor.putString(key, value).apply();
    }

    /**
     * 获取String的value
     */
    public static String getStringUser(String key, String defValue) {
        SharedPreferences sharedPreference = getSharedPreferenceUser();
        return sharedPreference.getString(key, defValue);
    }
    /**
     * 保存一个Boolean类型的值！
     */
    public static void putBooleanUser(String key, Boolean value) {
        SharedPreferences.Editor editor = getSharedPreferenceUser().edit();
        editor.putBoolean(key, value).apply();
    }

    /**
     * 获取boolean的value
     */
    public static boolean getBooleanUser(String key, Boolean defValue) {
        SharedPreferences sharedPreference = getSharedPreferenceUser();
        return sharedPreference.getBoolean(key, defValue);
    }
    /**
     * 保存一个int类型的值！
     */
    public static void putIntUser(String key, int value) {
        SharedPreferences.Editor editor = getSharedPreferenceUser().edit();
        editor.putInt(key, value).apply();
    }

    /**
     * 获取int的value
     */
    public static int getIntUser(String key, int defValue) {
        SharedPreferences sharedPreference = getSharedPreferenceUser();
        return sharedPreference.getInt(key, defValue);
    }
//**********************************************************************************************************************************************
    /**
     * 保存一个String类型的值！
     */
    public static void putString(String key, String value) {
        SharedPreferences.Editor editor = getSharedPreference().edit();
        editor.putString(key, value).apply();
    }

    /**
     * 获取String的value
     */
    public static String getString(String key, String defValue) {
        SharedPreferences sharedPreference = getSharedPreference();
        return sharedPreference.getString(key, defValue);
    }

    /**
     * 保存一个Boolean类型的值！
     */
    public static void putBoolean(String key, Boolean value) {
        SharedPreferences.Editor editor = getSharedPreference().edit();
        editor.putBoolean(key, value).apply();
    }

    /**
     * 获取boolean的value
     */
    public static boolean getBoolean(String key, Boolean defValue) {
        SharedPreferences sharedPreference = getSharedPreference();
        return sharedPreference.getBoolean(key, defValue);
    }

    /**
     * 保存一个int类型的值！
     */
    public static void putInt(String key, int value) {
        SharedPreferences.Editor editor = getSharedPreference().edit();
        editor.putInt(key, value).apply();
    }

    /**
     * 获取int的value
     */
    public static int getInt(String key, int defValue) {
        SharedPreferences sharedPreference = getSharedPreference();
        return sharedPreference.getInt(key, defValue);
    }
    /**
     * 保存一个float类型的值！
     */
    public static void putFloat(String key, float value) {
        SharedPreferences.Editor editor = getSharedPreference().edit();
        editor.putFloat(key, value).apply();
    }

    /**
     * 获取float的value
     */
    public static float getFloat(String key, Float defValue) {
        SharedPreferences sharedPreference = getSharedPreference();
        return sharedPreference.getFloat(key, defValue);
    }

    /**
     * 保存一个long类型的值！
     */
    public static void putLong(String key, long value) {
        SharedPreferences.Editor editor = getSharedPreference().edit();
        editor.putLong(key, value).apply();
    }

    /**
     * 获取long的value
     */
    public static long getLong(String key, long defValue) {
        SharedPreferences sharedPreference = getSharedPreference();
        return sharedPreference.getLong(key, defValue);
    }
    /**
     * 清空对应key数据
     */
    public static void remove(String key) {
        SharedPreferences.Editor editor = getSharedPreference().edit();
        editor.remove(key).apply();
    }
    /**
     * 清空SP数据
     */
    public static void clearAll() {
        SharedPreferences.Editor editor = getSharedPreferenceUser().edit();
        editor.clear().apply();
    }

    /**
     * 保存在手机里面的文件名
     */
    public static final String FILE_NAME = "xzff";

    /**
     * 保存数据的方法，我们需要拿到保存数据的具体类型，然后根据类型调用不同的保存方法
     */
    public static void putParam(Context context, String key, Object object) {

        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        if (object instanceof String) {
            editor.putString(key, (String) object);
        } else if (object instanceof Integer) {
            editor.putInt(key, (Integer) object);
        } else if (object instanceof Boolean) {
            editor.putBoolean(key, (Boolean) object);
        } else if (object instanceof Float) {
            editor.putFloat(key, (Float) object);
        } else if (object instanceof Long) {
            editor.putLong(key, (Long) object);
        } else {
            editor.putString(key, object.toString());
        }
        SharedPreferencesCompat.apply(editor);
    }

    //保存对象
    public static boolean setObjectToShare(Context context, Object object, String key) {
        // TODO Auto-generated method stub
        SharedPreferences share = PreferenceManager
                .getDefaultSharedPreferences(context);
        if (object == null) {
            SharedPreferences.Editor editor = share.edit().remove(key);
            return editor.commit();
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        // 将对象放到OutputStream中
        // 将对象转换成byte数组，并将其进行base64编码
        String objectStr = new String(Base64.encode(baos.toByteArray(),
                Base64.DEFAULT));
        try {
            baos.close();
            oos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        SharedPreferences.Editor editor = share.edit();
        // 将编码后的字符串写到base64.xml文件中
        editor.putString(key, objectStr);
        return editor.commit();
    }

    //获取对象
    public static Object getObjectFromShare(Context context, String key) {
        SharedPreferences sharePre = PreferenceManager
                .getDefaultSharedPreferences(context);
        try {
            String wordBase64 = sharePre.getString(key, "");
            // 将base64格式字符串还原成byte数组
            if (wordBase64 == null || wordBase64.equals("")) { // 不可少，否则在下面会报java.io.StreamCorruptedException
                return null;
            }
            byte[] objBytes = Base64.decode(wordBase64.getBytes(),
                    Base64.DEFAULT);
            ByteArrayInputStream bais = new ByteArrayInputStream(objBytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            // 将byte数组转换成product对象
            Object obj = ois.readObject();
            bais.close();
            ois.close();
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 得到保存数据的方法，我们根据默认值得到保存的数据的具体类型，然后调用相对于的方法获取值
     */
    public static Object getParam(Context context, String key, Object defaultObject) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        if (defaultObject instanceof String) {
            return sp.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer) {
            return sp.getInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float) {
            return sp.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long) {
            return sp.getLong(key, (Long) defaultObject);
        }

        return null;
    }

    /**
     * 移除某个key值已经对应的值
     */
    public static void remove(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(key);
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 清除所有数据
     */
    public static void clear(Context context) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 查询某个key是否已经存在
     */
    public static boolean contains(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        return sp.contains(key);
    }

    /**
     * 返回所有的键值对
     */
    public static Map<String, ?> getAll(Context context) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        return sp.getAll();
    }

    /**
     * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
     *
     */
    private static class SharedPreferencesCompat {
        private static final Method sApplyMethod = findApplyMethod();

        /**
         * 反射查找apply的方法
         */
        @SuppressWarnings({ "unchecked", "rawtypes" }) private static Method findApplyMethod() {
            try {
                Class clz = SharedPreferences.Editor.class;
                return clz.getMethod("apply");
            } catch (NoSuchMethodException e) {
            }

            return null;
        }

        /**
         * 如果找到则使用apply执行，否则使用commit
         */
        public static void apply(SharedPreferences.Editor editor) {
            try {
                if (sApplyMethod != null) {
                    sApplyMethod.invoke(editor);
                    return;
                }
            } catch (IllegalArgumentException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
            editor.commit();
        }
    }
}
